<?php namespace App\Http\Controllers\Api;

use App\Banner;
use App\DakaContent;
use App\DakaUser;
use App\DakaUserComment;
use App\DakaUserLike;
use App\Files;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\Message;
use App\User;
use App\Userinfo;
use App\UserRead;
use App\UserReadDay;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class DakaController extends Controller
{

    public function getBannerList(Request $request){
        $allBanner = Banner::orderBy("sort","asc")->orderBy("created_at","desc")->get();
        if(count($allBanner) > 0){
            foreach ($allBanner as $banner){
                /** @var Banner $banner */
                $banner->img_url = route("Api.File.showImageById",["id"=>$banner->img_id]);
            }
        }

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$allBanner]);
    }

    public function getActiveDaka(Request $request){
        $dakaId = !is_null($request->get("id")) ? $request->get("id") : 0;

        $thatActiveDaka = false;
        if($dakaId == 0){
            /** @var DakaContent $thatActiveDaka */
            $thatActiveDaka = DakaContent::whereIsActive(1)->first();
            if(!$thatActiveDaka)
                $thatActiveDaka = DakaContent::orderBy('id','desc')->first();
        }else{
            /** @var DakaContent $thatActiveDaka */
            $thatActiveDaka = DakaContent::whereId($dakaId)->first();
        }

        if(!$thatActiveDaka)
            return response()->json(["level"=>"error","message"=>"当前打卡不存在"]);

        $dakaUsers = DakaUser::whereDId($thatActiveDaka->id)->get();

        $dakaUserList = array();
        if(count($dakaUsers) > 0){
            foreach ($dakaUsers as $dakaUser){
                /** @var DakaUser $dakaUser */
                /** @var Userinfo $thatUserInfo */
                $thatUserInfo = Userinfo::whereUserId($dakaUser->user_id)->first();
                if($thatUserInfo){
                    $userinfo["id"] = $dakaUser->id;
                    $userinfo["photo_url"] = route("Api.File.showImageById",["id"=>$thatUserInfo->photo_id]);
                    $userinfo["nickname"]  = $thatUserInfo->nickname;
                    $userinfo["sex"]       = $thatUserInfo->sex;
                    $userinfo["content"]   = $dakaUser->content;
                    $userinfo["daka_time"] = date("Y-m-d H:i:s",strtotime($dakaUser->created_at));
                    $userinfo["keep_day"]  = DakaUser::whereUserId($dakaUser->user_id)->whereDId($dakaUser->d_id)->count();

                    /** @var DakaUser $thatFirstDakaUser */
                    $thatFirstDakaUser = DakaUser::whereDId($dakaUser->d_id)->orderBy("id","asc")->first();
                    if($thatFirstDakaUser){
                        $userinfo["join_time"] = date("Y-m-d",strtotime($thatFirstDakaUser->created_at));
                    }else{
                        $userinfo["join_time"] = date("Y-m-d",strtotime($dakaUser->created_at));
                    }

                    $allUserLikes = DakaUserLike::whereDuId($dakaUser->id)->get();
                    $userLikeNicknames = array();
                    foreach ($allUserLikes as $userLike){
                        /** @var DakaUserLike $userLike */
                        $thatUserLikeInfo = Userinfo::whereUserId($userLike->user_id)->first();
                        if($thatUserInfo){
                            $userLikeInfo["id"] = $userLike->id;
                            $userLikeInfo["nickname"] = $thatUserLikeInfo->nickname;
                            array_push($userLikeNicknames,$userLikeInfo);
                        }
                    }

                    $userinfo["like_list"] = $userLikeNicknames;

                    $comments = array();
                    $allUserComments = DakaUserComment::whereDuId($dakaUser->id)->get();
                    foreach ($allUserComments as $userComment){
                        /** @var DakaUserComment $userComment */
                        $thatCommentUserInfo = Userinfo::whereUserId($userComment->user_id)->first();
                        if($thatCommentUserInfo){
                            $userCommentInfo["id"]       = $userComment->id;
                            $userCommentInfo["nickname"] = $thatCommentUserInfo->nickname;
                            $userCommentInfo["content"]  = $userComment->content;
                            array_push($comments,$userCommentInfo);
                        }
                    }

                    $userinfo["comment_list"] = $comments;

                    array_push($dakaUserList,$userinfo);
                }
            }
        }

        $thatActiveDaka->daka_user_list = $dakaUserList;
        $thatActiveDaka->img_url        = route("Api.File.showImageById",["id"=>$thatActiveDaka->img_id]);

        $user = UserManager::isLogin($request);
        if($user){
            $selfDaka = DakaUser::whereDId($thatActiveDaka->id)->whereUserId($user->id)->first();
            if($selfDaka){
                $thatActiveDaka->has_clock = 1;
            }else{
                $thatActiveDaka->has_clock = 0;
            }

            /** @var UserRead $hasUserRead */
            $hasUserRead = UserRead::whereUserId($user->id)->whereDId($thatActiveDaka->id)->first();
            if(!$hasUserRead){
                $userRead = new UserRead();
                $userRead->d_id = $thatActiveDaka->id;
                $userRead->user_id = $user->id;
                $userRead->save();
            }

            $hasUserReadDay = UserReadDay::whereUserId($user->id)->whereReadDay(date("Y-m-d",time()))->first();
            if(!$hasUserReadDay){
                $hasUserReadDay = new UserReadDay();
                $hasUserReadDay->d_id     = $thatActiveDaka->id;
                $hasUserReadDay->user_id  = $user->id;
                $hasUserReadDay->read_day = date("Y-m-d",time());
                $hasUserReadDay->save();
            }
        }else{
            $thatActiveDaka->has_clock = 0;
        }

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$thatActiveDaka]);
    }

    public function sendDakaContent(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(["level"=>"error","message"=>"no_login","data"=>"no_login"]);

        $content     = $request->get("content");
        $type        = !is_null($request->get("type")) ? $request->get("type") : "daka";
        $dakaId      = $request->get("d_id");
        $dakaUserId  = $request->get("du_id");

        /** @var DakaContent $thatDaka */
        $thatDaka = DakaContent::whereId($dakaId)->first();
        if(!$thatDaka)
            return response()->json(["level"=>"error","message"=>"当前打卡文章不存在"]);

        $result = null;
        switch ($type){
            case "daka":
                //获取当天的最大时间和最小时间
                $ty = date('Y', time());
                $tm = date('m', time());
                $td = date('d', time());
                $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
                $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

                /** @var DakaUser $thatDakaUser */
                $thatDakaUser = DakaUser::whereUserId($user->id)->whereDId($thatDaka->id)->whereBetween("created_at",[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->orderBy("id","desc")->first();
                if($thatDakaUser){
                    return response()->json(["level"=>"error","message"=>"您今天在此任务中已经打过卡咯！"]);
                }

                //增加打卡人数
                /** @var DakaUser $hasDakaUser */
                $hasDakaUser = DakaUser::whereUserId($user->id)->whereDId($thatDaka->id)->first();
                if(!$hasDakaUser){
                    $thatDaka->user_count = (int)$thatDaka->user_count + 1;
                }
                $thatDaka->daka_count = (int)$thatDaka->daka_count + 1;
                $thatDaka->save();

                $thatDakaUser = new DakaUser();
                $thatDakaUser->user_id = $user->id;
                $thatDakaUser->content = $content;
                $thatDakaUser->d_id    = $dakaId;
                $thatDakaUser->save();

                $result = $thatDakaUser;

                //加积分
                UserManager::addIntegral($user,"daka");



                break;

            case "comment":
                /** @var DakaUser $thatDakaUser */
                $thatDakaUser = DakaUser::whereId($dakaUserId)->first();
                if(!$thatDakaUser){
                    return response()->json(["level"=>"error","message"=>"当前打卡内容不存在"]);
                }

                $newDakaUserComment = new DakaUserComment();
                $newDakaUserComment->user_id = $user->id;
                $newDakaUserComment->du_id   = $thatDakaUser->id;
                $newDakaUserComment->content = $content;
                $newDakaUserComment->save();

                //记录评论
                $newMessage = new Message();
                $newMessage->content = $content;
                $newMessage->user_id = $user->id;
                $newMessage->d_id    = $thatDakaUser->d_id;
                $newMessage->to_user_id = $thatDakaUser->user_id;
                $newMessage->save();

                //加积分
                UserManager::addIntegral($user,"comment");

                $result = $newDakaUserComment;
        }

        return response()->json(["level"=>"success","message"=>"感谢您的参与","data"=>$result]);
    }

    public function setUserLike(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(["level"=>"error","message"=>"no_login","data"=>"no_login"]);

        $duId = $request->get("du_id");

        $thatDakaUser = DakaUser::whereId($duId)->first();
        if(!$thatDakaUser)
            return response()->json(["level"=>"error","message"=>"当前打卡内容不存在"]);

        /** @var DakaUserLike $thatUserLike */
        $thatUserLike = DakaUserLike::whereUserId($user->id)->whereDuId($duId)->first();

        $type = "add";
        if($thatUserLike){
            $thatUserLike->delete();
            $type = "del";
        }else{
            $thatUserLike = new DakaUserLike();
            $thatUserLike->user_id = $user->id;
            $thatUserLike->du_id   = $duId;
            $thatUserLike->save();

            //加积分
            UserManager::addIntegral($user,"like");

            $type = "add";
        }

        /** @var Userinfo $thatUserInfo */
        $thatUserInfo = Userinfo::whereUserId($user->id)->first();

        if($thatUserInfo){
            $thatUserLike->nickname = $thatUserInfo->nickname;
        }else{
            $thatUserLike->nickname = "";
        }

        $thatUserLike->type = $type;

        return response()->json(["level"=>"success","message"=>"感谢你的支持","data"=>$thatUserLike]);
    }

    public function getDakaList(Request $request){
        $keyword = $request->get("keyword");

        $allDaka = null;
        if(!is_null($keyword)){
            $allDaka = DakaContent::where("title","like","%".$keyword."%")->orderBy("id","asc")->get();
        }else{
            $allDaka = DakaContent::orderBy("id","asc")->get();
        }

        if(count($allDaka) > 0){
            foreach ($allDaka as $daka){
                /** @var DakaContent $daka */
                $daka->img_url = route("Api.File.showImageById",["id"=>$daka->img_id]);
            }
        }

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$allDaka]);
    }

    public function buildShareImg(Request $request){
        $id    = $request->get('id');
        $page  = $request->get('page');
        $scene = !is_null($request->get('scene')) ? $request->get('scene') : 'daka';

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(["level"=>"error","message"=>"no_login","data"=>"no_login"]);

        /** @var DakaContent $thatDaka */
        $thatDaka = DakaContent::whereId($id)->first();

        if(!$thatDaka)
            return response()->json(["level"=>"error","message"=>"当前打卡内容不存在"]);

        $qrcodeImgContent = null;
        if($thatDaka->qrcode_img_id != 0){
            $qrcodeImg = Images::whereId($thatDaka->qrcode_img_id)->first();
            if(!$qrcodeImg){
                $qrcodeImgContent = WechatLogin::getWxUnlimitQrcodeByToken($scene,'');

                $newFile = FileManager::saveFileByFileContent($qrcodeImgContent,"wx_qrcode.jpg",'');

                $qrcodeImg = new Images();
                $qrcodeImg->file_id = $newFile->id;
                $qrcodeImg->img_name= "wx_qrcode.jpg";
                $qrcodeImg->img_type= $newFile->file_type;
                $qrcodeImg->save();

                $thatDaka->qrcode_img_id = $qrcodeImg->id;
                $thatDaka->save();
            }
        }else{
            $qrcodeImgContent = WechatLogin::getWxUnlimitQrcodeByToken($scene,'');

            $newFile = FileManager::saveFileByFileContent($qrcodeImgContent,"wx_qrcode.jpg",'');

            $qrcodeImg = new Images();
            $qrcodeImg->file_id = $newFile->id;
            $qrcodeImg->img_name= "wx_qrcode.jpg";
            $qrcodeImg->img_type= $newFile->file_type;
            $qrcodeImg->save();

            $thatDaka->qrcode_img_id = $qrcodeImg->id;
            $thatDaka->save();
        }

        $token = CryptoJSAES::encrypt($user->wx_openid,env('AES_KEY'));
        $shareImgUrl = route("Api.Daka.showShareImg")."?daka_token=".$token."&id=".$thatDaka->id;

        return \response()->json(['level'=>"success",'message'=>"生成二维码成功","data"=>$shareImgUrl]);
    }

    public function showShareImg(Request $request){
        $id   = $request->get('id');
        $user = UserManager::isLogin($request);

        /** @var DakaContent $thatDaka */
        $thatDaka = DakaContent::whereId($id)->first();
        if(!$thatDaka)
            return response()->json(["level"=>"error","message"=>"当前打卡内容不存在"]);

        $dakaQrcodeImg = Images::whereId($thatDaka->qrcode_img_id)->first();
        if(!$dakaQrcodeImg)
            return response()->json(["level"=>"error","message"=>"打卡二维码生成失败"]);

        /** @var Files $qrcodeFile */
        $qrcodeFile = $dakaQrcodeImg->files;
        $qrcodeContent = $qrcodeFile->getContent();

        //开始合成图片
        $shareBackImg   = Image::make(url('share/share-img.jpg'));
        $shareBackModel = Image::make(url('share/share-background.png'));
        $zhiwenImg      = Image::make(url('share/zhiwen.png'));
        $qrcodeImg      = Image::make($qrcodeContent);

        $shareBackImg->insert($shareBackModel, 'center');

        //用户头像
        $userInfo       = Userinfo::whereUserId($user->id)->first();
        $userPhotoImage = Images::whereId($userInfo->photo_id)->first();

        $userPhotoContent = null;
        if($userPhotoImage){
            /** @var Files $userPhotoFile */
            $userPhotoFile = $userPhotoImage->files;
            $userPhotoContent= Image::make($userPhotoFile->getContent());
        }else{
            $userPhotoContent= Image::make(url("images/default-photo.png"));
        }

        $userPhotoContent->resize(80,80);
        $shareBackImg->insert($userPhotoContent,"top",220,90);

        //指纹
        $zhiwenImg->resize(70,80);
        $shareBackImg->insert($zhiwenImg,"bottom-right",140,60);

        //小程序二维码
        $qrcodeImg->resize(80,80);
        $shareBackImg->insert($qrcodeImg,"bottom-right",225,60);

        $shareBackImg->text($userInfo->nickname, 220, 180, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
            $font->size(17);
            $font->color('#696969');
            $font->align('center');
            $font->valign('top');
            $font->angle(0);
        });

        $len = mb_strlen($thatDaka->title,'utf-8');
        if($len > 9){
            $title = mb_substr($thatDaka->title,0,15,'utf-8') . "...";
        }else{
            $title = $thatDaka->title;
        }

        $shareBackImg->text($title, 220, 210, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
            $font->size(15);
            $font->color('#696969');
            $font->align('center');
            $font->valign('top');
            $font->angle(0);
        });

        $myReadNumCount = UserRead::whereUserId($user->id)->count();
        $myReadDayCount = UserReadDay::whereUserId($user->id)->count();

        $shareBackImg->text($myReadDayCount, 120, 300, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
            $font->size(30);
            $font->color('#696969');
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $shareBackImg->text($myReadNumCount, 270, 300, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
            $font->size(26);
            $font->color('#696969');
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $response = response()->make($shareBackImg->encode('png'));
        $response->header('Content-Type', 'image/png');
        return $response;
    }

    public function getToken(Request $request)
    {
        $openid = $request->get("openid");
        $token = CryptoJSAES::encrypt($openid,env('AES_KEY'));

        echo $token;
    }

}